package com.eqdd.yiqidian.ui.discover.makerspace

import android.app.Activity
import android.content.Intent
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.base.BaseActivity
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.IndustriesBean
import com.eqdd.yiqidian.box.ItemDecoration.DividerLineItemDecoration
import com.eqdd.yiqidian.http.DialogCallBack
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.kotlin.deleteDialog
import com.eqdd.yiqidian.ui.SingleChooseActivity
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_maker_industry.*
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.startActivityForResult
import org.jetbrains.anko.toast
import java.util.*

/**
 * Created by jhj on 18-8-10.
 */
class MakerIndustryActivity : BaseActivity() {

    private var density: Int = 2
    private var industryBean: IndustriesBean? = null

    private var industrySlimAdapter: SlimAdapterEx<IndustriesBean.IndustryBean>? = null
    private var postSlimAdapter: SlimAdapterEx<IndustriesBean.PostBean>? = null
    private var serviceIndustrySlimAdapter: SlimAdapterEx<IndustriesBean.IndustryBean>? = null
    private var servicePostSlimAdapter: SlimAdapterEx<IndustriesBean.PostBean>? = null
    private var modeSlimAdapter: SlimAdapterEx<IndustriesBean.ModeBean>? = null
    private var timeSlimAdapter: SlimAdapterEx<IndustriesBean.TimeBean>? = null


    companion object {
        const val ACTION_INDUSTRY = 1000
        const val ACTION_POST = 1001
        const val ACTION_SERVICE_INDUSTRY = 1002
        const val ACTION_SERVICE_POST = 1003
        const val ACTION_WAY = 1004
        const val ACTION_TIME = 1005
        const val UPDATE_WAY = 1006
        const val UPDATE_TIME = 1007
    }

    override fun initBinding() {
        setContentView(R.layout.activity_maker_industry)
        density = resources.displayMetrics.density.toInt()
        initTopTitleBar(View.VISIBLE, "所属行业")
        industryView()
        postView()
        serviceIndustryView()
        servicePostView()
        modeView()
        timeView()
    }

    override fun initData() {
        OkGo.post<HttpResult<IndustriesBean>>(HttpConfig.BASE_URL + HttpConfig.INDUSTRY_GET)
                .params("userGuid", user.guid)
                .execute(object : DialogCallBack<HttpResult<IndustriesBean>>(this) {
                    override fun onSuccess(response: Response<HttpResult<IndustriesBean>>?) {
                        val result = response?.body()
                        if (result?.status == 200) {
                            industryBean = result.items
                            industryBean?.industry?.let {
                                industrySlimAdapter?.updateData(it)
                            }
                            industryBean?.post?.let {
                                postSlimAdapter?.updateData(it)
                            }
                            industryBean?.serviceIndustry?.let {
                                serviceIndustrySlimAdapter?.updateData(it)
                            }
                            industryBean?.servicePost?.let {
                                servicePostSlimAdapter?.updateData(it)
                            }
                            industryBean?.serviceMode?.let {
                                modeSlimAdapter?.updateData(it)
                            }
                            industryBean?.serviceTime?.let {
                                timeSlimAdapter?.updateData(it)
                            }
                        } else {
                            toast(result?.msg ?: "查询失败")
                        }
                    }

                })
    }

    override fun setView() {
        iv_industry_add.onClick {
            startActivityForResult<SingleChooseActivity>(ACTION_INDUSTRY, Config.TYPE to 2, Config.TITLE to "所在行业")
        }
        iv_post_add.onClick {
            startActivityForResult<SingleChooseActivity>(ACTION_POST, Config.TYPE to 1, Config.TITLE to "所在岗位")
        }
        iv_service_industry_add.onClick {
            startActivityForResult<SingleChooseActivity>(ACTION_SERVICE_INDUSTRY, Config.TYPE to 2, Config.TITLE to "所属行业")
        }
        iv_service_post_add.onClick {
            startActivityForResult<SingleChooseActivity>(ACTION_SERVICE_POST, Config.TYPE to 1, Config.TITLE to "所属岗位")
        }
        iv_way_add.onClick {
            startActivityForResult<IndustryWayActivity>(ACTION_WAY, Config.TYPE to 1)
        }
        iv_time_add.onClick {
            startActivityForResult<IndustryTimeActivity>(ACTION_TIME)
        }
    }


    private fun industryView() {
        val list = arrayListOf<IndustriesBean.IndustryBean>()
        recycler_industry.layoutManager = LinearLayoutManager(this)
        recycler_industry.addItemDecoration(DividerLineItemDecoration(this).setLeftPadding(10 * density).setRightPadding(10 * density))
        industrySlimAdapter = SlimAdapterEx.create()
                .register<IndustriesBean.IndustryBean>(R.layout.list_item_181, SlimInjector<IndustriesBean.IndustryBean> { data, injector ->
                    injector?.text(R.id.tv_content, data?.industry)
                })
                .attachTo(recycler_industry)
                .updateData(list as List<IndustriesBean.IndustryBean>?) as SlimAdapterEx<IndustriesBean.IndustryBean>?
        ItemClickSupport.addTo(recycler_industry)
                .setOnItemLongClickListener { recyclerView, position, v ->
                    val data = industrySlimAdapter?.getDataItem(position)
                    deleteDialog(HttpConfig.BASE_URL + HttpConfig.INDUSTRY_INDUSTRY_DELETE, "是否删除“${data?.industry}”？", "industryId" to data?.id, "type" to 0, isFinish = false) {
                        initData()
                    }

                    true
                }
    }

    private fun postView() {
        val list = arrayListOf<IndustriesBean.PostBean>()
        recycler_post.layoutManager = LinearLayoutManager(this)
        recycler_post.addItemDecoration(DividerLineItemDecoration(this).setLeftPadding(10 * density).setRightPadding(10 * density))
        postSlimAdapter = SlimAdapterEx.create()
                .register<IndustriesBean.PostBean>(R.layout.list_item_181, SlimInjector<IndustriesBean.PostBean> { data, injector ->
                    injector?.text(R.id.tv_content, data?.post)
                })
                .attachTo(recycler_post)
                .updateData(list as List<IndustriesBean.PostBean>?) as SlimAdapterEx<IndustriesBean.PostBean>?
        ItemClickSupport.addTo(recycler_post)
                .setOnItemLongClickListener { recyclerView, position, v ->
                    val data = postSlimAdapter?.getDataItem(position)
                    deleteDialog(HttpConfig.BASE_URL + HttpConfig.INDUSTRY_POST_DELETE, "是否删除“${data?.post}”？", "postId" to data?.id, "type" to 0, isFinish = false) {
                        initData()
                    }
                    true
                }
    }

    private fun serviceIndustryView() {
        val list = arrayListOf<IndustriesBean.IndustryBean>()
        recycler_service_industry.layoutManager = LinearLayoutManager(this)
        recycler_service_industry.addItemDecoration(DividerLineItemDecoration(this).setLeftPadding(10 * density).setRightPadding(10 * density))
        serviceIndustrySlimAdapter = SlimAdapterEx.create()
                .register<IndustriesBean.IndustryBean>(R.layout.list_item_181, SlimInjector<IndustriesBean.IndustryBean> { data, injector ->
                    injector?.text(R.id.tv_content, data?.industry)
                })
                .attachTo(recycler_service_industry)
                .updateData(list as List<IndustriesBean.IndustryBean>?) as SlimAdapterEx<IndustriesBean.IndustryBean>?
        ItemClickSupport.addTo(recycler_service_industry)
                .setOnItemLongClickListener { recyclerView, position, v ->
                    val data = serviceIndustrySlimAdapter?.getDataItem(position)
                    deleteDialog(HttpConfig.BASE_URL + HttpConfig.INDUSTRY_INDUSTRY_DELETE, "是否删除“${data?.industry}”？", "industryId" to data?.id, "type" to 1, isFinish = false) {
                        initData()
                    }
                    true
                }
    }

    private fun servicePostView() {
        val list = arrayListOf<IndustriesBean.PostBean>()
        recycler_service_post.layoutManager = LinearLayoutManager(this)
        recycler_service_post.addItemDecoration(DividerLineItemDecoration(this).setLeftPadding(10 * density).setRightPadding(10 * density))
        servicePostSlimAdapter = SlimAdapterEx.create()
                .register<IndustriesBean.PostBean>(R.layout.list_item_181, SlimInjector<IndustriesBean.PostBean> { data, injector ->
                    injector?.text(R.id.tv_content, data?.post)
                })
                .attachTo(recycler_service_post)
                .updateData(list as List<IndustriesBean.PostBean>?) as SlimAdapterEx<IndustriesBean.PostBean>?
        ItemClickSupport.addTo(recycler_service_post)
                .setOnItemLongClickListener { recyclerView, position, v ->
                    val data = servicePostSlimAdapter?.getDataItem(position)
                    deleteDialog(HttpConfig.BASE_URL + HttpConfig.INDUSTRY_POST_DELETE, "是否删除“${data?.post}”？", "postId" to data?.id, "type" to 1, isFinish = false) {
                        initData()
                    }
                    true
                }
    }


    private fun modeView() {
        val list = arrayListOf<IndustriesBean.ModeBean>()
        recycler_way.layoutManager = LinearLayoutManager(this)
        recycler_way.addItemDecoration(DividerLineItemDecoration(this).setLeftPadding(10 * density).setRightPadding(10 * density))
        modeSlimAdapter = SlimAdapterEx.create().register<IndustriesBean.ModeBean>(R.layout.list_item_176, SlimInjector<IndustriesBean.ModeBean> { data, injector ->
            val type = when (data?.type) {
                0 -> "线下服务"
                1 -> "电话服务"
                2 -> "线上服务"
                else -> ""
            }
            injector?.text(R.id.tv_type, String.format(Locale.CHINA, "服务方式：%s", type))
                    ?.text(R.id.tv_start, String.format(Locale.CHINA, "小时/元：%s", data?.oneHourPrice))
                    ?.text(R.id.tv_end, String.format(Locale.CHINA, "天/元：%s", data?.oneDayPrice))
        }).attachTo(recycler_way).updateData(list as List<IndustriesBean.ModeBean>?) as SlimAdapterEx<IndustriesBean.ModeBean>?

        ItemClickSupport.addTo(recycler_way)
                .setOnItemClickListener { recyclerView, position, v ->
                    val data = modeSlimAdapter?.getDataItem(position)
                    startActivityForResult<IndustryWayActivity>(UPDATE_WAY, "data" to data)
                }
                .setOnItemLongClickListener { recyclerView, position, v ->
                    val bean = modeSlimAdapter?.getDataItem(position)
                    val type = when (bean?.type) {
                        0 -> "线下服务"
                        1 -> "电话服务"
                        2 -> "线上服务"
                        else -> ""
                    }
                    deleteDialog(HttpConfig.BASE_URL + HttpConfig.INDUSTRY_WAY_DELETE, "是否删除“${type}”？", "modeId" to bean?.id, isFinish = false) {
                        initData()
                    }
                    true
                }
    }

    private fun timeView() {
        val list = arrayListOf<IndustriesBean.TimeBean>()
        recycler_time.layoutManager = LinearLayoutManager(this)
        recycler_time.addItemDecoration(DividerLineItemDecoration(this).setLeftPadding(10 * density).setRightPadding(10 * density))
        timeSlimAdapter = SlimAdapterEx.create()
                .register<IndustriesBean.TimeBean>(R.layout.list_item_176, SlimInjector<IndustriesBean.TimeBean> { data, injector ->
                    val type = when (data?.type) {
                        0 -> "白天"
                        1 -> "晚上"
                        else -> ""
                    }
                    injector?.text(R.id.tv_type, String.format(Locale.CHINA, "服务时间：%s", type))
                            ?.text(R.id.tv_start, String.format(Locale.CHINA, "开始时间：%s", data?.startTime))
                            ?.text(R.id.tv_end, String.format(Locale.CHINA, "结束时间：%s", data?.endTime))
                })
                .attachTo(recycler_time)
                .updateData(list as List<IndustriesBean.TimeBean>?) as SlimAdapterEx<IndustriesBean.TimeBean>?
        ItemClickSupport.addTo(recycler_time)
                .setOnItemClickListener { recyclerView, position, v ->
                    val data = timeSlimAdapter?.getDataItem(position)
                    startActivityForResult<IndustryTimeActivity>(UPDATE_TIME, "data" to data)
                }
                .setOnItemLongClickListener { recyclerView, position, v ->
                    val data = timeSlimAdapter?.getDataItem(position)
                    val type = when (data?.type) {
                        0 -> "白天"
                        1 -> "晚上"
                        else -> ""
                    }

                    deleteDialog(HttpConfig.BASE_URL + HttpConfig.INDUSTRY_TIME_DELETE, "是否删除“${type}”？", "timeId" to data?.id, isFinish = false) {
                        initData()
                    }
                    true
                }
    }

    private fun uploadIndustry(industry: String, type: String) {
        OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.INDUSTRY_INDUSTRY_ADD)
                .params("userGuid", user.guid)
                .params("type", type) // //0:添加自己的行业，1：添加服务的行业
                .params("Industry", industry)
                .execute(object : DialogCallBack<HttpResult<*>>(this) {
                    override fun onSuccess(response: Response<HttpResult<*>>?) {
                        val result = response?.body()
                        if (result?.status == 200) {
                            initData()
                        } else {
                            toast(result?.msg ?: "添加失败")
                        }
                    }
                })
    }

    private fun uploadPost(post: String, type: String) {
        OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.INDUSTRY_POST_ADD)
                .params("userGuid", user.guid)
                .params("type", type) // //0:添加自己的行业，1：添加服务的行业
                .params("post", post)
                .execute(object : DialogCallBack<HttpResult<*>>(this) {
                    override fun onSuccess(response: Response<HttpResult<*>>?) {
                        val result = response?.body()
                        if (result?.status == 200) {
                            initData()
                        } else {
                            toast(result?.msg ?: "添加失败")
                        }
                    }
                })
    }

    private fun uploadMode(bean: IndustriesBean.ModeBean) {
        OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.INDUSTRY_WAY_ADD)
                .params("userGuid", user.guid)
                .params("type", bean.type)
                .params("oneDayPrice", bean.oneDayPrice)
                .params("oneHourPrice", bean.oneHourPrice)
                .execute(object : DialogCallBack<HttpResult<*>>(this) {
                    override fun onSuccess(response: Response<HttpResult<*>>?) {
                        val result = response?.body()
                        if (result?.status == 200) {
                            initData()
                        } else {
                            toast(result?.msg ?: "添加失败")
                        }
                    }
                })
    }

    private fun updateMode(bean: ModeBean) {
        OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.INDUSTRY_WAY_UPDATE)
                .params("userGuid", user.guid)
                .params("type", bean.type)
                .params("modeId", bean.modeId)
                .params("oneDayPrice", bean.oneDayPrice)
                .params("oneHourPrice", bean.oneHourPrice)
                .execute(object : DialogCallBack<HttpResult<*>>(this) {
                    override fun onSuccess(response: Response<HttpResult<*>>?) {
                        val result = response?.body()
                        if (result?.status == 200) {
                            initData()
                        } else {
                            toast(result?.msg ?: "修改失败")
                        }
                    }
                })
    }

    private fun uploadTime(bean: IndustriesBean.TimeBean) {
        OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.INDUSTRY_TIME_ADD)
                .params("userGuid", user.guid)
                .params("type", bean.type)
                .params("startTime", bean.startTime)
                .params("endTime", bean.endTime)
                .execute(object : DialogCallBack<HttpResult<*>>(this) {
                    override fun onSuccess(response: Response<HttpResult<*>>?) {
                        val result = response?.body()
                        if (result?.status == 200) {
                            initData()
                        } else {
                            toast(result?.msg ?: "添加失败")
                        }
                    }
                })
    }

    private fun updateTime(bean: IndustriesBean.TimeBean) {
        OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.INDUSTRY_TIME_UPDATE)
                .params("userGuid", user.guid)
                .params("type", bean.type)
                .params("timeId", bean.id)
                .params("startTime", bean.startTime)
                .params("endTime", bean.endTime)
                .execute(object : DialogCallBack<HttpResult<*>>(this) {
                    override fun onSuccess(response: Response<HttpResult<*>>?) {
                        val result = response?.body()
                        if (result?.status == 200) {
                            initData()
                        } else {
                            toast(result?.msg ?: "修改失败")
                        }
                    }
                })
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            val str = data?.getStringExtra("data") ?: return
            when (requestCode) {
                ACTION_INDUSTRY -> {
                    uploadIndustry(str, "0")
                }
                ACTION_POST -> {
                    uploadPost(str, "0")
                }
                ACTION_SERVICE_INDUSTRY -> {
                    uploadIndustry(str, "1")
                }
                ACTION_SERVICE_POST -> {
                    uploadPost(str, "1")
                }
                ACTION_WAY -> {
                    val mode = Gson().fromJson<IndustriesBean.ModeBean>(str, object : TypeToken<IndustriesBean.ModeBean>() {}.type)
                    uploadMode(mode)
                }
                ACTION_TIME -> {
                    val time = Gson().fromJson<IndustriesBean.TimeBean>(str, object : TypeToken<IndustriesBean.TimeBean>() {}.type)
                    uploadTime(time)
                }
                UPDATE_WAY -> {
                    val mode = Gson().fromJson<ModeBean>(str, object : TypeToken<ModeBean>() {}.type)
                    updateMode(mode)
                }
                UPDATE_TIME -> {
                    val time = Gson().fromJson<IndustriesBean.TimeBean>(str, object : TypeToken<IndustriesBean.TimeBean>() {}.type)
                    updateTime(time)
                }
            }
        }
    }

    class ModeBean {
        val oneHourPrice: String = ""
        val oneDayPrice: String = ""
        val type: Int = -1
        val modeId: Int = -1
    }
}